$(function () {
    // Fetch URIS from local storage and convert to an array.
    var getUris = function () {
        var uris = window.localStorage.getItem("uris_to_print");
        if (uris) {
            return uris.split(',');
        }
        return [];
    }

    // attach a click even to the 'starred' menu item (in _Layout.cshtml)
    // this will cause a submit of the form in custom_scripts.cshtml to peform a search for
    // starred records
    // See the 81 sample if you wish to use a link rather than a form post to do this search
    // the benefit of the form post is that we avoid any limits on the length of a URL.
    $('#menu_print_link').click(function () {
        var uris = getUris();
        if (uris.length > 0) {
            $("#print_form_q").val("uri:" + uris.join());
            $("#print_form_pageSize").val(uris.length);
            $("#print_form").submit();
        } else {
            alert("You have not starred any records.")
        }
        return false;
    });

    // append an icon after the second cell in each search result row
    $(".trim-list tbody tr td:nth-child(2)")
    .each(function (index, value) {
        var url = $(value).parent().find("a").first().attr("href");
        var uri = url.substr(url.lastIndexOf('/') + 1);
        $(value).append(
            '<i class="print-icon icon-star'
            + ($.inArray(uri, getUris()) > -1 ? "" : "-empty")
            + ' pull-right" data-record-uri="'
            + uri + '"></i>');
    });

    // add a click even to each icon to either add or remove the record URI to/from
    // the localStorage
    $(".print-icon")
    .each(function (index, value) {
        $(value).click(
            function () {
                var uris = getUris();
                var uri = $(this).attr("data-record-uri");
                if (uris.indexOf(uri) > -1) {
                    uris.splice(uris.indexOf(uri), 1);
                } else {
                    uris.push(uri);
                }
                $(this).toggleClass('icon-star icon-star-empty');

                window.localStorage.setItem("uris_to_print", uris.join());
                return false;
            })
    });
});